<template lang="pug">
  v-card
    AddAssetStockChangeHistoryDialog(ref="addDialog", :asset="asset" @addSuccess="onChangeHistoryAdded")
    v-toolbar(flat)
      v-spacer
      v-toolbar-items
        v-btn(text @click="refresh") 刷新
        v-btn(color="primary" text @click="showAddHistoryDialog") 新增
    v-data-table( :headers="headers"
      :options.sync="options"
      :items="items"
      loading-text="数据加载中..."
      no-data-text="未找到数据"
      :server-items-length="totalItems"
      :footer-props="footerProps"
      :loading="isLoading"
    )
      template(v-slot:item.action_id='{ item }')
        span {{ getColumnValue(item, 'action.name') }}
      template(v-slot:item.user_id='{ item }')
        span {{ getColumnValue(item, 'user.name') }}
</template>

<script lang="ts">
  import Vue, {VueConstructor} from 'vue'
  import mixins from '../mixins/PaginateDataTableMixin'
  import AddAssetStockChangeHistoryDialog from './asset_stock_add_change_history_dialog'
  import {mapActions} from 'vuex'
  import {AxiosPromise, AxiosResponse} from 'axios'

  export default (Vue as VueConstructor<Vue & {
    $loading: (title: string) => void,
    refresh: () => void,
    $refs: {
      addDialog: AddAssetStockChangeHistoryDialog
    },
    fetchAssetStockChangeHistory: (id: string, opt: any) => AxiosPromise
  }>).extend({
    props: ['asset', 'view'],
    mixins: [mixins],
    methods: {
      ...mapActions('assetStock', {
        fetchAssetStockChangeHistory: 'fetchAssetStockChangeHistory',
        addChangeHistory: 'addChangeHistory',
        fetchAssetStock: 'fetchAssetStock',
      }),
      refreshAsset(){
        this.fetchAssetStock(this.asset.id).then((response: AxiosResponse) => {
          if (!response.data.error) {
            this.asset = Object.assign(this.asset, response.data.result)
          }
        })
      },
      onChangeHistoryAdded() {
        this.refresh()
        this.refreshAsset()
      },
      showAddHistoryDialog() {
        this.$refs.addDialog.toggle()
      },
      add() {
        this.$loading('保存中...')
        this.addChangeHistory().then().finally(() => {
          this.$loading.close()
        })
      },
      fetchData(opt: any): AxiosPromise {
        return this.fetchAssetStockChangeHistory([this.asset.id, opt])
      }
    },
    components: { AddAssetStockChangeHistoryDialog },
    data() {
      return {
        headers: [
          { text: '操作', value: 'action_id', sortable: false },
          { text: '数量', value: 'quantity', sortable: false },
          { text: '描述', value: 'comment', sortable: false },
          { text: '时间', value: 'created_at', sortable: false },
          { text: '操作人', value: 'user_id', sortable: false },
        ]
      }
    }
  })
</script>
